package com.grape.transaction.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.grape.transaction.rabbitmq.constrant.CommConstrant;
import com.grape.transaction.rabbitmq.entity.OrderEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 描述:CreateOrderConsumer  补单操作
 * @author: myx
 * @date: 2019/6/10
 * Copyright © 2019-grape. All rights reserved.
 */
@Component
public class CreateOrderConsumer {


	/**
     * @param message
     * @param headers
     * @param channel
     * @throws Exception
	 */
	@RabbitListener(queues = "order_create_queue")
	public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception {
		Thread.sleep(500);
		String messageId = message.getMessageProperties().getMessageId();
		String msg = new String(message.getBody(), "UTF-8");
		System.out.println("补单消费者接收消息:" + msg + ",消息id:" + messageId);
		JSONObject jsonObject = JSONObject.parseObject(msg);
		String orderId = jsonObject.getString("orderId");
		// 判断订单是否存在，如果不存在 实现自动补单机制
		if (CommConstrant.commMap.contains(orderId)) {
			System.out.println(orderId+"===订单已经存在 无需补单");
			//丢弃消息
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			return;
		}
		// 订单不存在 ，则需要进行补单

		OrderEntity orderEntity = new OrderEntity();
		orderEntity.setOrderName("订单名称");
		// 价格是300元
		orderEntity.setOrderMoney("300");
		// 状态为 未支付
		orderEntity.setStatus(0);
		try {
			int orderResult=1;
			System.out.println(orderId+"===订单不存在进行补单操作...");
			if (orderResult >= 0) {
				// 手动签收消息,通知mq服务器端删除该消息
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				System.out.println(orderId+"===补单成功");
			}
		} catch (Exception e) {
			// 丢弃该消息
			channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
		}
	}
}